package com.wolfman.wolfchat.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wolfman.wolfchat.mapper.MessageMapper;
import com.wolfman.wolfchat.po.Message;
import com.wolfman.wolfchat.po.User;
import com.wolfman.wolfchat.service.MessageService;
import com.wolfman.wolfchat.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @Title
 * @Description
 * @Author WolfMan
 * @Date 2022/1/15 0:41
 * @Email 2370032534@qq.com
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Resource
    MessageMapper messageMapper;

    @Resource
    UserService userService;

    /**
     * 查询聊天记录
     *
     * @param fromUserId
     * @param toUserId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Message> selectMessageByUserIdAndPage(Integer fromUserId, Integer toUserId, Integer pageNum, Integer pageSize) {
        User fromUser = userService.selectByUserId(fromUserId);
        User toUser = userService.selectByUserId(toUserId);
        PageHelper.startPage(pageNum, pageSize);
        List<Message> messageList = messageMapper.selectMessageByUserIdAndPage(fromUserId, toUserId);
        messageList.forEach((message -> {
            if (message.getFromUserId().equals(fromUser.getId())) {
                message.setFromUser(fromUser);
            } else {
                message.setFromUser(toUser);
            }
        }));
        //反转集合
        Collections.reverse(messageList);
        return new PageInfo<>(messageList);
    }
}
